package mudfox.controller;

import mudfox.entity.Position;
import mudfox.repository.PositionRepository;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/*
@RestController注解，相当于@Controller+@ResponseBody两个注解的结合，
返回json数据不需要在方法前面加@ResponseBody注解了，
但使用@RestController这个注解，就不能返回jsp,html页面，
视图解析器无法解析jsp,html页面
 */

@RestController
@RequestMapping("/pos")
public class PositionController {
    static Logger log = LoggerFactory.getLogger(PositionController.class);

    @Autowired
    private PositionRepository positionRepository;

    @GetMapping("")
    public Map<String, String> index() {
        Map<String, String> map = new HashMap<>();
        map.put("reply", "Running");
        return map;
    }

    @GetMapping("/add")
    public Map<String, String> addPosition(@RequestParam String topic,
                                           @RequestParam String label,
                                           @RequestParam(value = "detail", defaultValue = "", required = false) String detail,
                                           @RequestParam(value = "addition", defaultValue = "", required = false) String addition) {
        Position pos = new Position();
        pos.setTopic(topic);
        pos.setLabel(label);
        pos.setDetail(detail);
        pos.setAddition(addition);

        Map<String, String> map = new HashMap<>();
        Position reply = positionRepository.save(pos);
        if (reply.getId() > 1)
            map.put("reply", "Done");
        else
            map.put("reply", "Error");
        return map;
    }

    @GetMapping("/label/{label}")
    public Iterable<Position> getPositions(@PathVariable("label") String label) {
        // log.debug("Input: " + label);
        return positionRepository.findByLabelContaining(label);
    }

    @GetMapping("/topic/{topic}")
    public Iterable<Position> getPositionByTopic(@PathVariable("topic") String topic) {
        return positionRepository.findByTopic(topic);
    }

    @GetMapping("/topics")
    public Iterable<String> getTopics() {
        return positionRepository.getTopics();
    }

    @PostMapping("/api/{pos}")
    public Map<String, String> addItem(@PathVariable("pos") Position pos) {
        positionRepository.save(pos);

        String label = pos.getLabel();
        Map<String, String> reply = new HashMap<>();
        reply.put("reply", label + "已添加");
        return reply;
    }
}
